package com.hooper.apibackend.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/04/12/12:55
 */
@Aspect
@Component
@Slf4j
public class AuthInterceptor {
    /**
     * 流量染色判断
     */
    @Before("execution(* com.hooper.apibackend.controller.*.*(..))")
    public void authCheck(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String name = joinPoint.getSignature().getName();
        log.info("method name: {}", name);
        String identity = request.getHeader("X-Request-Auth");
        log.info("凭证 ： "+identity);
        // 流量染色判断
        if (StringUtils.isBlank(identity)) {
            log.error(request.getRequestURI(), "the request not go through api-gateway");
            log.error("host:" + request.getRemoteHost());
            throw new RuntimeException("the request not go through api-gateway");
        }
    }
}
